﻿using Orleans;
using Orleans.Runtime;

namespace OrleansURLShortener
{
    /// <summary>
    /// 短Url粒度實現
    /// </summary>
    /// <param name="state">狀態</param>
    public sealed class UrlShortenerGrain(
    [PersistentState(stateName: "url",storageName: "urls")]
        IPersistentState<UrlDetails> state)
    : Grain, IUrlShortenerGrain
    {
        /// <summary>
        /// 永久保存原始URL和相應短URL
        /// </summary>
        /// <param name="fullUrl">原始URL</param>
        public async Task SetUrl(string fullUrl)
        {
            state.State = new()
            {
                ShortenedRouteSegment = this.GetPrimaryKeyString(),
                FullUrl = fullUrl
            };
            await state.WriteStateAsync();
        }

        /// <summary>
        /// 獲取原始URL
        /// </summary>
        /// <returns>短URL</returns>
        public Task<string> GetUrl() =>
            Task.FromResult(state.State.FullUrl);
    }

    /// <summary>
    /// URL詳情
    /// </summary>
    [GenerateSerializer, Alias(nameof(UrlDetails))]
    public sealed record class UrlDetails
    {
        /// <summary>
        /// 完整URL
        /// </summary>
        [Id(0)]
        public string FullUrl { get; set; } = "";

        /// <summary>
        /// 短URL
        /// </summary>
        [Id(1)]
        public string ShortenedRouteSegment { get; set; } = "";
    }
}
